﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AccidentCards
{
    public partial class MainForm : Form
    {
        private AccidentData m_Data = null;
        private DataTable m_table = null;

        public MainForm()
        {
            InitializeComponent();
        }

        /** @fn void OnNewMessage()
         * @brief Обработчик события OnNewMessage
         * @details Обработчик пользовательского события @ref NewMessage класса @ref DecisionData.
         *      Выполняется при поступленнии(изменении, удалении) сообщений по подписке
         */
        void OnNewMessage()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;

            // Check if the event was generated from another
            // thread and needs invoke instead
            if (i.InvokeRequired)
            {
                AccidentData.NewMessage tempDelegate = new AccidentData.NewMessage(OnNewMessage);
                i.BeginInvoke(tempDelegate, null);
                return;
            }

            // If not coming from a separate thread
            // we can access the Windows form controls
            LoadMessages();
        }


        private DataTable FilterView(DataTable table)
        {
            DataTable dt = new DataTable();
            dt.BeginLoadData();
            DataColumn[] columns = {    new DataColumn("id",         System.Type.GetType("System.Int64")),
                                        new DataColumn("Вид ДТП",                System.Type.GetType("System.String")),
                                        new DataColumn("Код региона",         System.Type.GetType("System.Int32")),
                                        new DataColumn("Тип операции",  System.Type.GetType("System.String")),
                                        new DataColumn("регион",         System.Type.GetType("System.String"))
                                    };
            dt.Columns.AddRange(columns);

            foreach (DataRow row in table.Rows)
            {
                object[] newRow = new object[columns.Length];
                newRow[0] = row["id"];
                newRow[1] = row["Вид ДТП"];
                newRow[2] = row["Код региона"];
                newRow[3] = row["Тип операции"];
                newRow[4] = row["регион"];
                
                DataRow r = dt.LoadDataRow(newRow, true);
            }

            dt.EndLoadData();

            return dt;
        }

        /** @fn void LoadMessages()
        * @brief Заполняет таблицу отображения карточками событий
        * @details Заполняет таблицу и применяет визуальные изменения к ней
        */
        private void LoadMessages()
        {
            accidentList.DataSource = null;
            DateTime? startDate = null;
            if (currentDayAccidents.Checked)
            {
                DateTime tempDateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0, 0);
                if (tempDateTime > DateTime.Now)
                    startDate = tempDateTime.AddDays(-1);
                else
                    startDate = tempDateTime;
            }
            m_table = m_Data.GetMessages(startDate);
            accidentList.DataSource = FilterView(m_table);
            accidentList.Columns[0].Visible = false;
            accidentList.Columns[1].Width = 250;
            accidentList.Columns[2].Width = 250;
            accidentList.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCellsExceptHeader;
            accidentList.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;            
            
        }

        private void menuItemSettings_Click(object sender, EventArgs e)
        {
            SettingsForm frmSettings = new SettingsForm();
            frmSettings.ShowDialog();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            lblUserName.Text = dbServices.globalUserWindows;

            m_Data = new AccidentData();
            LoadMessages();
        }

        private void menuItemExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void menuItemCreateCard_Click(object sender, EventArgs e)
        {
            AccidentCardForm frmAccident = new AccidentCardForm();
            frmAccident.ShowDialog();
            LoadMessages();
        }

        private void updateTimer_Tick(object sender, EventArgs e)
        {
            LoadMessages();
        }


        private void accidentList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            Int64 id = Convert.ToInt64(accidentList.Rows[e.RowIndex].Cells[0].Value);
            AccidentCardForm frmAccident = new AccidentCardForm(id);
            frmAccident.ShowDialog();
            LoadMessages();
        }
    }
}
